namespace('is.app', new function(){

    this.init = function() {
        // Register the upper login button
        is.outlet.register('login', {
            'click': function(event) {
                is.layout.load('east', 'Sign in', '/login/', function() {
                    var token = $('#token').html();
                    is.region.get('east').find('.token').replaceWith(token);
                });
            }
        });

        // Register the logout action
        is.outlet.register('logout', {
            'click': function(event) {
                $.get('/logout/', function(data){
                    location.reload();
                });
            }
        });

        // Register the login submit actions
        is.outlet.register('login_submit', {
            'click': function(event) {
                var service = event.data.target.attr('href').substring(1);
                window.location = '/login/' + service + '/';
            },
            'submit': function(event) {
                $.post('/login/', $('#login_form').serialize(), function(data){
                   location.reload();
                });
            }
        });

        // Register the registration button
        is.outlet.register('user_register', {
            'click': function(event) {
                is.layout.load('east', 'Register', '/register/', function() {
                    var token = $('#token').html();
                    is.region.get('east').find('.token').replaceWith(token);
                });
            }
        });

        // Register the register submit actions
        is.outlet.register('user_submit', {
            'submit': function(event) {
                $.post('/register/', $('#register_form').serialize(), function(data){
                    if(!data['success']) {
                         $('#register_form .ui-state-error').html('Invalid form data');
                         $('#register_form .ui-state-error').show();
                    } else {
                         location.reload();
                    }
                });
            }
        });

        // Capture the search form
        is.outlet.register('search', {
            'submit': function(event) {
                var text = $('#search_text').val();
                if(text.length > 3) {
                    is.layout.load('main', 'Loading Results', '/loading/');
                    is.layout.load('main', 'Results for \'' + text + '\'', '/search?q=' + text);
                } else is.notify.msg('Your search text is too short.<br/>Please try another phrase.')
            }
        });

        // Load the product view
        is.outlet.register('product', {
            'click': function(event) {
                var product = event.data.target.attr('href').substring(1);
                is.layout.load('main', 'Product ' + product, '/product/' + product);
            }
        });

        // Bind the navigation buttons to actions
        is.outlet.register('navi', {
            'click': function(event) {
                switch(event.data.target.attr('panel')) {
                    case 'cart':
                        if(is.region.isopen('east')
                            && is.region.view('east') == is.region.conv('Cart'))
                            is.region.toggle('east');
                        else is.layout.load('east', 'Cart', '/cart/view/', true);
                        break;
                    case 'friend':
                        if(is.region.isopen('west')
                            && is.region.view('west') == is.region.conv('Friends'))
                            is.region.toggle('west');
                        else is.layout.load('west', 'Friends', '/profile/friends/', true);
                        break;
                }

            }
        });

        // Cart functionality
        is.outlet.register('cart_add', {
            'click': function(event) {
                var obj = event.data.target;
                var args = {
                    'product_id': obj.attr('pid'),
                    'title':  obj.attr('ttl'),
                    'price':  obj.attr('prc'),
                    'vendor': obj.attr('vnd'),
                    'purchase_url': obj.attr('url')
                }

                $.getJSON('/cart/add', args, function(data){
                    if(data['success']) {
                        is.notify.msg('Added item \'' + args['title'] + '\' to your cart');
                        if(is.region.view('east') == is.region.conv('Cart')) {
                            is.layout.load('east', 'Cart', '/cart/view/', true);
                        }
                    }
                });
            }
        });
        is.outlet.register('cart_remove', {
            'click': function(event) {
                var index = event.data.target.attr('index');
                var title = event.data.target.attr('title');
                $.getJSON('/cart/remove', {'index' : index}, function(data){
                    if(data['success']) {
                        is.notify.msg('Removed item \'' + title + '\' from your cart');
                        if(is.region.view('east') == is.region.conv('Cart')) {
                            is.layout.load('east', 'Cart', '/cart/view/', true);
                        }
                    }
                });
            }
        });

        is.outlet.register('purchase_link', {
            'click': function(event) {
                window.open(event.data.target.attr('url'));
            }
        });

        // Profile functionality
        is.outlet.register('profile', {
        	'click': function(event) {
        		var userid = event.data.target.attr('userid');
        		if(userid != null) {
        			is.layout.load('main', 'Profile', '/profile/' + userid + '/');
        		} else {
        			is.layout.load('main', 'Profile', '/profile/');
        		}
        	}
        });

        // Friend functionality
        is.outlet.register('friend', {
        	'click': function(event) {
        		var uid = event.data.target.attr('href').substring(1);
        		var action = event.data.target.attr('action');
        		$.getJSON('/profile/friends/' + action, {'uid': uid }, function(data){
        			if(data['success']) {
                        if(is.region.view('west') == is.region.conv('Friends')) {
                            is.layout.load('west', 'Friends', '/profile/friends/', true);
                        }
        			} else {
        				console.log('failed to add friend');
        			}
        		});
        	},
        	'submit': function(event) {
        		var name = $('#friend_add_form .text').val();
        		$.getJSON('/profile/friends/add', {'name': name }, function(data){
        			if(data['success']) {
                        if(is.region.view('west') == is.region.conv('Friends')) {
                            is.layout.load('west', 'Friends', '/profile/friends/', true);
                        }
        			} else {
        				console.log('failed to add friend');
        			}
        		});
        	}
        });
        is.outlet.register('friend_remove', {
        	'click': function(event) {
        		var userid = event.data.target.attr('userid');
        		$.getJSON('/profile/remove_friend/???/', {'index' : index}, function(data){
                    if(data['success']) {
                        is.notify.msg('Removed item \'' + title + '\' from your cart');
                        if(is.region.view('east') == is.region.conv('Cart')) {
                            is.layout.load('east', 'Cart', '/cart/view/', true);
                        }
                    }
                });
        	}
        });

        is.outlet.register('theme', {
            'change': function(event) {
                var name = $('#theme').val();
                is.theme.load(name);
                $.get('/session', {'theme': name}, function(data){
                    if(data['success']) {
                        is.notify.msg('Updated theme');
                    }
                });
            },
            'mouseenter': function(event) {
                $('#theme').removeClass('ui-state-default');
                $('#theme').addClass('ui-state-hover');
            },
            'mouseleave': function(event) {
                $('#theme').removeClass('ui-state-hover');
                $('#theme').addClass('ui-state-default');
            }
        });

        // Hack to expand the login button
        $(document).oneTime(200, is.layout.menu.resizeAll);

        /*$(document).oneTime(10, function(){
            is.theme.load(site_theme)
            $('#theme').children().each(function(){
                console.log($(this));
            });
        });*/
    }

    is.register('init', this);
});

$(document).ready(function(){
    is.theme.load(site_theme);
    is.init();
});
